package com.card.framework.spring;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.context.HttpSessionSecurityContextRepository;
import org.springframework.web.filter.OncePerRequestFilter;

public class LoginAjaxFilter extends OncePerRequestFilter {

    private static final Logger log = LoggerFactory.getLogger(LoginAjaxFilter.class);

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
       throws ServletException, IOException {

        if (!isAjaxRequest(request)) {
            filterChain.doFilter(request, response);
            return;
        }

        RedirectResponseWrapper redirectResponseWrapper = new RedirectResponseWrapper(response);

        filterChain.doFilter(request, redirectResponseWrapper);

        Map<String, String> map = new HashMap<String, String>();
        if (redirectResponseWrapper.getRedirect() != null) {

            String redirectURL = redirectResponseWrapper.getRedirect();

            HttpSession httpSession = request.getSession();

            if (redirectURL.indexOf("login") != -1) {
                if (redirectURL.indexOf("login_error=1") != -1) {
                    map.put("success", "false");
                }
            }
            else {
                SecurityContext ctx = (SecurityContext) httpSession.getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY);
                if (ctx != null) {
                    Authentication auth = ctx.getAuthentication();
                    UserDetails user = (UserDetails) auth.getPrincipal();
                    if (user != null) {
                        map.put("username", user.getUsername());
                        map.put("success", "true");
                    } else {
                        map.put("success", "false");
                        map.put("errorMsg", "error");
                    }
                } else {
                    map.put("success", "false");
                }
            }
            try {
            	JSONObject json=JSONObject.fromObject(map); 
                response.getWriter().write(json.toString());
            } catch (Exception e) {
                log.error("{}",e.getMessage());
            }
        }

    }

    protected boolean isAjaxRequest(HttpServletRequest request) {
        String ajax = request.getParameter("ajax");
        if ("".equals(ajax) || ajax == null) {
            return false;
        }
        return true;
    }

}